'use client'

import { useState } from 'react'
import { uploadFile } from '@repo/oss-uploader'

export default function UploadPage() {
  const [progress, setProgress] = useState(0)
  const [uploading, setUploading] = useState(false)
  const [result, setResult] = useState<string>('')
  const [error, setError] = useState<string>('')

  const handleFileUpload = async (file: File) => {
    setUploading(true)
    setProgress(0)
    setResult('')
    setError('')
    
    try {
      const url = await uploadFile({
        file,
        onProgress: (percent) => {
          setProgress(percent)
        }
      })
      
      setResult(url)
    } catch (err) {
      setError(err instanceof Error ? err.message : '上传失败')
    } finally {
      setUploading(false)
    }
  }

  return (
    <div className="max-w-2xl mx-auto p-6">
      <h1 className="text-3xl font-bold mb-8">文件上传示例</h1>
      
      <div className="space-y-6">
        <div>
          <label className="block text-sm font-medium mb-2">
            选择文件
          </label>
          <input
            type="file"
            onChange={(e) => {
              const file = e.target.files?.[0]
              if (file) handleFileUpload(file)
            }}
            disabled={uploading}
            className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
          />
        </div>

        {uploading && (
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span>上传进度</span>
              <span>{Math.round(progress * 100)}%</span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2">
              <div 
                className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                style={{ width: `${progress * 100}%` }}
              />
            </div>
          </div>
        )}

        {result && (
          <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
            <h3 className="font-medium text-green-800 mb-2">上传成功！</h3>
            <p className="text-sm text-green-700 break-all">{result}</p>
          </div>
        )}

        {error && (
          <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
            <h3 className="font-medium text-red-800 mb-2">上传失败</h3>
            <p className="text-sm text-red-700">{error}</p>
          </div>
        )}
      </div>

      <div className="mt-8 p-4 bg-gray-50 rounded-lg">
        <h3 className="font-medium mb-2">使用说明</h3>
        <ul className="text-sm text-gray-600 space-y-1">
          <li>• 支持任意类型的文件上传</li>
          <li>• 自动分片上传大文件</li>
          <li>• 实时显示上传进度</li>
          <li>• 需要配置 /api/get-sts 接口</li>
        </ul>
      </div>
    </div>
  )
} 